package cn.jtfadmin.activiti.config;

import cn.jtfadmin.base.lang.common.security.UserDetails;
import cn.jtfadmin.base.lang.config.user.UserHolder;
import org.activiti.engine.IdentityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 */
@Configuration
public class UserAutionFilterConfiguration implements WebMvcConfigurer, HandlerInterceptor {
    @Autowired
    private IdentityService identityService;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this);
    }


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        UserDetails userDetails = UserHolder.getUserDetails();
        if(userDetails!=null){
            identityService.setAuthenticatedUserId(userDetails.getUsername());
        }else {
            identityService.setAuthenticatedUserId(null);
        }
        return true;
    }


    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
        identityService.setAuthenticatedUserId(null);
    }




}
